<template>
  <div id="uploadExcel">
    <el-upload class="upload-demo" drag :auto-upload="false" action="upload" :file-list="fileList" :on-change="handleChange" ref="upload">
      <!-- <i class="el-icon-upload"></i> -->
      <img src="../../../../assets/images/import_upload.png" alt="" />
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div class="el-upload__tip" slot="tip">说明：请使用系统模版导入，也可以使用已有Excel表格进行匹配表头字段导入</div>
    </el-upload>
    <div class="dowloads">
      <el-popover placement="right" width="400" trigger="manual" v-model="showTreeData1">
        <span slot="reference" class="dowload" @click="downloadTemplate1(1)"><i class="iconfont">&#xe64d;</i>标准模板</span>
        <div style="padding: 10px">
          <div class="block">
            <el-input placeholder="输入关键字进行过滤" v-model="filterText"></el-input>
          </div>
          <div class="box" style="height: 340px; overflow: auto">
            <el-tree ref="tree" :data="treeData" show-checkbox node-key="id" :default-expanded-keys="['00000000-0000-0000-0000-000000000000']" :render-content="renderContent" highlight-current :filter-node-method="filterNode" :props="defaultProps"></el-tree>
          </div>
          <div class="dialog-footer">
            <el-button type="primary" @click="showTreeData1 = false">取 消</el-button>
            <el-button @click="downloadTemplate(1)" type="primary">确 认</el-button>
          </div>
        </div>
      </el-popover>
      <span v-if="moduleCode == 0 && !this.isEdit">|</span>
      <span v-if="moduleCode == 0 && !this.isEdit" style="margin-left: 20px" class="dowload" @click="downloadTemplate(2)"><i class="iconfont">&#xe64d;</i>极简模板</span>
    </div>
    <div class="Mask" v-if="showTreeData1" @click="showTreeData1 = false"></div>
  </div>
</template>
<script>
import { mapTreeAddIcon } from "@/util/util";
export default {
  name: "uploadExcel",
  props: {
    file: {
      type: Object,
    },
    isEdit: {
      type: Boolean,
    },
    moduleCode: {
      type: Number,
    },
    isMoreListEdit: {
      type: Boolean,
    },
  },
  data() {
    return {
      //excel文件
      fileList: [],
      showTreeData1: false,
      treeData: [],
      filterText: "",
      defaultProps: {
        children: "childrens",
        label: "name",
      },
    };
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    if (this.file) {
      this.fileList.push(this.file);
    } else {
      this.fileList = [];
    }
    if (this.isEdit) {
      this.getSubCompanyView();
    }
  },
  activated() {
    if (this.file) {
      this.fileList.push(this.file);
    } else {
      this.fileList = [];
    }
    if (this.isEdit) {
      this.getSubCompanyView();
    }
  },
  methods: {
    reloadExcel() {
      if (this.file) {
        this.fileList.push(this.file);
      } else {
        this.fileList = [];
      }
      if (this.isEdit) {
        this.getSubCompanyView();
      }
    },
    renderContent(h, { node, data, store }) {
      return (
        <span class="custom-tree-node">
          <img width="15px" src={data.icons} />
          <span title={node.label} style="margin-left:5px;font-size: 12px;position: relative;top: -1px;">
            {node.label.length > 20 ? node.label.slice(0, 20) + "..." : node.label}
          </span>
        </span>
      );
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    //获取最高层节点
    getHigherCheckedNodes(store) {
      const checkedNodes = [];
      const traverse = function (node) {
        const childNodes = node.root ? node.root.childNodes : node.childNodes;
        childNodes.forEach((child) => {
          if (child.checked) {
            checkedNodes.push(child.data);
          }
          if (child.indeterminate) {
            traverse(child);
          }
        });
      };
      traverse(store);
      return checkedNodes;
    },
    getLowCheckedNodes() {
      let handleAfterNode = this.$refs.tree.getCheckedNodes();
      const userArr = handleAfterNode.filter((item) => item.type == 3);
      return userArr;
    },
    handleData(data, parentObj = {}) {
      // 关联父子数据  1   1-1   1-1-1    1-1-1-1   n-n-n-n
      data.map((item, index) => {
        if (parentObj.relatedId) {
          item.relatedId = parentObj.relatedId + `-${index + 1}`;
        } else {
          item.relatedId = index + 1 + "";
        }
        if (item.childrens && item.childrens.length) {
          this.handleData(item.childrens, item);
        }
      });
      return data;
    },
    async getSubCompanyView() {
      //公司部门子集人员树
      const { data } = await this.$api.importUser.GetEmployeeTree();
      this.treeData = JSON.parse(JSON.stringify(mapTreeAddIcon(this.handleData([data.data]))));
      // this.updateDefaultCheckKeys();
    },
    //上传文件
    handleChange(files) {
      if (files.name.split(".")[1].indexOf("xls") > -1 || files.name.split(".")[1].indexOf("xlsx") > -1) {
        this.fileList = [files];
        this.$emit("getFile", files);
      } else {
        this.$message.warning("导入文件只允许excel类型");
        this.$refs.upload.clearFiles();
        return false;
      }
    },
    async downloadTemplate1(type) {
      let res = this.isEdit && this.moduleCode == 0;
      let res1 = this.moduleCode != 0 && this.isMoreListEdit;
      if (res || res1) {
        this.showTreeData1 = true;
      } else {
        await this.downloadTemplate(type);
      }
    },
    //下载模板
    async downloadTemplate(type) {
      const download = ({ data, fileName }) => {
        const blob = new Blob([data], { type: "application/vnd.ms-excel" });
        const blobUrl = URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = blobUrl;
        a.download = `${fileName}.xlsx`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(blobUrl);
      };
      let params = {
        moduleCode: this.moduleCode,
        isSimple: false,
      };
      if (type != 1) {
        params.isSimple = true;
      }
      if (this.isEdit) {
        let handleAfterNode = this.getHigherCheckedNodes(this.$refs.tree.store);
        // 仅人员
        handleAfterNode = this.getLowCheckedNodes();
        // roleid
        const ids = handleAfterNode.map((i) => i.id);
        params.data = ids;
      }

      const { data } = await this.$api.importUser[this.isEdit ? "GetImportTemplatePost" : "GetImportTemplate"](params);
      download({ data, fileName: type == 1 ? "标准模板" : "极简模板" });
      this.showTreeData1 = false;
    },
  },
};
</script>
<style lang="less" scoped>
#uploadExcel {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  flex-flow: column;
  justify-content: center;
  align-items: center;
  :deep(.upload-demo){
    height: 70%;
    max-height: 300px;
    .el-upload{
      height: calc(100% - 50px);
      .el-upload-dragger{
        height: 100% !important;
      }
    }
  }
  .Mask {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
  }
  :deep(.el-upload-dragger ){
    width: 600px;
    height: 300px;
    display: flex;
    flex-flow: column;
    align-items: center;
    justify-content: center;
    img {
      width: 100px;
    }
  }
  .dowloads {
    width: 600px;
    // margin-top: 18px;
    font-size: 14px;
    .dowload {
      color: #39a4ed;
      margin-right: 20px;
      cursor: pointer;
    }
    .dowload:hover {
      color: black;
    }
  }
}
</style>
